<template>
  <div>
    <template v-for="(tag, _index) in checkTags" :key="_index">
      <el-tag
        style="margin-right: 3px"
        :closable="!disable"
        @close="check(tag)"
      >
        {{ tag.name }}
      </el-tag>
    </template>
    <el-button
      class="button-new-tag ml-1"
      size="small"
      @click="drawerTag = true"
      v-if="!disable"
    >
      标签配置
    </el-button>

    <el-drawer v-model="drawerTag" title="标签选择" :append-to-body="true">
      <template v-for="(tag, _index) in tags" :key="_index">
        <el-tag
          style="margin: 3px"
          type="info"
          closable
          @close="remove(tag.id)"
          :hit="tag.checked"
          @click="check(tag)"
        >
          {{ tag.name }}
        </el-tag>
      </template>
      <el-input
        v-if="inputVisible"
        ref="inputRef"
        v-model="inputValue"
        class="ml-1 w-20"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button
        style="display: inline-block; margin: 7px"
        v-else
        class="button-new-tag ml-1"
        size="small"
        @click="showInput"
      >
        + New Tag
      </el-button>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, nextTick, watch, computed } from "vue";
import useTags from "./useTags";

const props = defineProps({
  checks: {
    type: Array,
    default: () => [],
  },
  disable: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:checks"]);

const { tags, remove, add } = useTags(props.checks);

// const checkIds = computed(() => {
//   return props.checks;
// });

const checkTags = computed({
  get() {
    return tags.value.filter((item) => (props.checks || []).includes(item.id));
  },
  set(val) {
    emit("update:checks", val);
    tags.value.forEach((item) => (item.checked = false));
    tags.value
      .filter((item) => val.includes(item.id))
      .forEach((item) => (item.checked = true));
  },
});

const check = (tag) => {
  let _index = (props.checks || []).findIndex((item) => item === tag.id);
  let tempArr = [...props.checks];
  if (_index > -1) {
    tempArr.splice(_index, 1);
  } else {
    tempArr.push(tag.id);
  }
  checkTags.value = tempArr;
};

// watch(
//   () => props.checks,
//   (newVal) => {
//     console.log(newVal);
//     checkTags.value = newVal;
//   }
// );

// watch(checkTags, (val) => {
//   console.log(val);
//   emit("update:checks", val);
// });

const inputRef = ref();
const inputVisible = ref(false);
const inputValue = ref("");
const drawerTag = ref(false);

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  add(inputValue.value);
  inputValue.value = "";
  inputVisible.value = false;
};
</script>
